home *** CD-ROM | disk | FTP | other *** search
/ HyperLib 1997 Winter - Disc 1 / HYPERLIB-1997-Winter-CD1.ISO.7z / HYPERLIB-1997-Winter-CD1.ISO / オンラインウェア / PRG / Prograph Reference Manual.sit / Prograph Reference Manual / Prograph Reference 8-End.rsrc / TEXT_145.txt < prev    next >
Text File  |  1995-10-26  |  28KB  |  657 lines

  1.  
  2. t Writing XPrims *557*
  3.  
  4. This section uses four example XPrims to illustrate how to write and build your own XPrims. 
  5.  
  6. XPrims, if written properly, will run in both interpreted and compiled applications without alteration.  The interpreter specific code should be bracketed by the #if _INTERPRETER and #endif statements. This code is then included only if the _INTERPRETER flag is set to one. To use the XPrims as part of a compiled application, you need only set the flag to zero.
  7.  
  8. Code which is interpreter specific and should be bracketed includes:  
  9.  
  10. q A Main routine (described below) which loads your primitives into the Prograph interpreter窶冱 primitive table, initializes the global data register, and calls the AddPrimitive supplied function for each XPrim to be added;
  11.  
  12. q    calls to the CallPrimitive function;
  13.  
  14. q code to check for data related errors.
  15.  
  16. XPrim names must follow the naming conventions for universal methods. This is because the compiler uses the same conventions for primitives and for universal methods. The compiler automatically identifies all C functions which begin with 窶弑_窶 as universal methods.
  17.  
  18. The name of each XPrim窶冱 C function must be of the form U_name. Any non-alphanumeric characters in the name must be replaced by their two-character, hexadecimal ASCII code and delimited by underscores. For example, the primitive point-in-rect? is represented as U_point_2D_in_2D_rect_3F_ ( 2D and 3F being the ASCII representations of '-' and '?' respectively).
  19.  
  20. There are several differences between interpreted and compiled code which should be kept in mind when writing XPrims:  
  21.  
  22. q Prograph primitives can be called directly in compiled code. You must, however, set the arity with the SETARITY macro (described above in 窶廣rity Macros窶) before doing so. For example, the code to call the show primitive with three inputs would be:  
  23.  
  24. #if _INTERPRETER
  25.  CallPrimitive( 窶彌Pshow窶, 0x0300, myString1, myInteger,
  26.               myString2 );
  27. #else
  28.  SETARITY( 3, 0 );
  29.  U_show( myString1, myInteger, myString2 );
  30. #endif
  31.  
  32.  
  33. q The supplied functions AddPrimitive and CallPrimitive are not used in compiled code.
  34.  
  35. q The index parameter of list functions (ListEmptySlot, for instance) is four bytes in compiled code and two bytes in interpreted code.
  36.  
  37. q The size parameter of list and string functions (StrStretchString, for instance) is four bytes in compiled code and two bytes in interpreted code
  38.  
  39. q The slot parameter of MakeC_List is four bytes in compiled code and two bytes in interpreted code
  40.  
  41. Function Return Values *559*
  42.  
  43. When a primtive completes without error, its C function should return PCF_TRUE for its integer return parameter.  The only exception is a boolean primtive with no output root; such a method, if it completes successfully, conveys its boolean result by passing either PCF_TRUE or PCF_FALSE.
  44.  
  45.  
  46. _______________________________________
  47. NOTE:    In the flags passed to AddPrimitive, PF_CTRL should be specified for a primitive that can return either PCF_TRUE or PCF_FALSE; this forces a default next-case control on the calling operation. PF_VAR should be specified if the primitive has an optional boolean output.
  48. ---------------------------------------
  49.  
  50.  
  51. Error conditions are reported to the interpreter by returning one of the following error codes:  
  52.  
  53. /* primitive execution errors */
  54.  
  55. #define PRIMERR_ARITY     0x0100 /* wrong # of inputs/outputs */
  56. #define PRIMERR_TYPE      0x0200 /* wrong type of input */
  57. #define PRIMERR_ARITH     0x0300 /* arithmetic error */
  58. #define PRIMERR_VALUE     0x0400 /* input value out of range */
  59. #define PRIMERR_COMPARE     0x0500 /* incomparable types */
  60.  
  61.  
  62. These error codes are recognized by the Prograph interpreter only. In compiled code PCF_TRUE and PCF_FALSE are the only valid return codes.  
  63.  
  64. In interpreted code the following error checks should be made:  
  65.  
  66. All primitives, whether of fixed or variable arity, should verify their arity and return PRIMERR_ARITY if the arity is not correct. 
  67.  
  68. The types of all inputs should be validated. If an input type is incorrect, PRIMERR_TYPE should be returned. 
  69.  
  70. If the range of an input value is not acceptable, PRIMERR_VALUE should be returned.
  71. For PRIMERR_TYPE and PRIMERR_VALUE errors, the ordinal number of the input containing the bad data should be added to the error value. For example, if the second input of a primitive should have been an integer but was a boolean instead, the value returned should be PRIMERR_TYPE+2.
  72.  
  73. In compiled code values such as PRIMERR_ARITY, PRIMERR_VALUE and PRIMERR_TYPE should never be returned by methods. Error checking should be done when running in the interpreter but not in compiled code.  A C compiler directive flag, _INTERPRETER can be used to bracket error checking code. The XPrim examples illustrate this technique.
  74.  
  75. The next two sections describe how to build a set of example XPrims as compiled and interpreted code respectively. Instructions are given for THINK C and MPW C. The example XPrims themselves are described in a separate section.
  76.  
  77.  XPrims in Interpreted Code *560*
  78.  
  79. The Prograph interpreter does not recognize XPrims in the same way as the compiler. For each XPrim, you must supply a 'STR#' resource containing the primitive窶冱 name and help information. This information is used to identify primitives and is also displayed in Prograph窶冱 ヒ僮nfo窶ヲ dialog. You must also have a main routine which calls AddPrimitive for each primitive. 
  80.  
  81. Each 'STR#' must consist of three strings:   the mnemonic names of the input and output arguments, the types of the input and output arguments, and a brief description of what the primitive does.  Three strings must be present in each 'STR#' resource, even if they are empty. 
  82.  
  83. The 'STR#'s resource number is used to map the code for a primitive onto its associated 'STR#'.  The 'STR#' resource number can be any number between 1 and 32K but must be unique within its file.
  84.  
  85. The 'STR#'s resource name becomes the name of the Prograph primitive. Only the first 19 characters of a primitive窶冱 name are recognized uniquely. 
  86.  
  87. Each 'STR#' resource should be marked as purgeable.
  88.  
  89. The value of a global data register (A4 in THINK C, A5 in MPW C) is set up at the beginning of the main routine.  The data register is automatically restored by the interpreter before an XPrim is called. This allows the code resource to have global or static data. 
  90.  
  91. In the main routine, a call is made to AddPrimitive for each of your primitives as shown in the following example:   
  92.  
  93.  AddPrimitive( 4, 0x0001, PF_USER, 0, &U_get_2D_filter );
  94.  
  95. The first argument to AddPrimitive is the resource number of the primitive窶冱 associated 'STR#' resource.
  96.  
  97. The second argument to AddPrimitive describes the default arity given to the primitive窶冱 calling operation when created in a Prograph program. Note that this is not necessarily the same arity that is passed to the call to the primitive.
  98.  
  99. The third argument is a set of flags. All XPrims need to have the value PF_USER set as one of the flags. A fixed-arity primitive, which is created without a control, should have a flags argument of PF_USER. If the primitive has variable-arity, the flag PF_VAR should be set. If the calling operation is to be created with a default next-case control, the flag PF_CTRL should be set. These flags are defined in X_constants.h.
  100. The fourth argument should always be zero.
  101.  
  102. The last argument is the address of the primitive窶冱 code.
  103.  
  104. Building Interpreted XPrims Using THINK C *561*
  105.  
  106. This section describes how to build and use the example XPrims using THINK C. 
  107. u    Create a new THINK C project.
  108.  
  109. u    Select Set Project from the Project menu, set the project type to 窶廚ode Resource,窶 set Type to 'TGSC', and set ID to 1. 
  110.  
  111. u    Set File Type to 'TGSC' and Creator to TGSL. 
  112.  
  113. u    Add to the project the version of MacTraps supplied with THINK C, and the files XP_support_I and example_XPrims.c supplied with Prograph. 
  114.  
  115. u Make sure the _INTERPRETER flag in X_includes.h is set to 1.
  116.  
  117. u    Compile and build the code resource into a file called example_XPrims.
  118.  
  119. u Move example_XPrims into the same folder as Prograph and the example XPrims are ready to use.
  120.  
  121.  
  122. _______________________________________
  123. NOTE:    'TGSC' resources can be numbered arbitrarily. The maximum size of a 'TGSC' code resource is 32K bytes. However, if your code exceeds 32K, you can use the mutli-segment code resource option in THINK C.
  124. ---------------------------------------
  125.  
  126.  
  127. Creating the 'STR#' Resources Using THINK C *561*
  128.  
  129. Each primitive should have a corresponding 'STR#' resource containing the primitive窶冱 name and help information; this will be displayed in Prograph窶冱 ヒ僮nfo窶ヲ dialog. 
  130.  
  131. In THINK C when the resource file name is the project name suffixed with '.rsrc,' the 'STR#' resources are automatically copied over whenever the code resource is built.  You can copy an 'STR#' resource from the example_XPrims_I.マ\.rsrc file and use it as a template for your own primitives.
  132.  
  133. The file example_XPrims_I.マ\.r contains the 'STR#' resources for the example XPrims.  You can use this file as a template for creating your own 'STR#' resources. Run this file through RMaker , and then use ResEdit to copy the resources into the file created when your code resource is built.
  134.  
  135. Here are the contents of example_XPrims_I.マ\.r :  
  136.  
  137. example_XPrims_I.マ\.rsrc
  138.  
  139. TYPE STR#
  140.  
  141. list-average, 1 (32)
  142. 3
  143. Inputs:   TheList¥0D++
  144. Outputs:   TheAverage
  145. Inputs:   list¥0D++
  146. Outputs:   real
  147. Accept a list of numbers, return the average.
  148.  
  149. input-average, 2 (32)
  150. 3
  151. Inputs:  TheNumber; [ TheNumber; 窶ヲ]¥0D++
  152. Outputs:  TheAverage
  153. Inputs:   number; [number; 窶ヲ]¥0D++
  154. Outputs:   real
  155. Accept 1 to n numeric inputs, return the average.
  156.  
  157. point-in-rect?, 3 (32)
  158. 3
  159. Inputs:   ThePoint; TheRect¥0D++
  160. Outputs:   [TheResult]
  161. Inputs:   point; rect¥0D++
  162. Outputs:   [boolean]
  163. ThePoint is in TheRect? With output the result is TRUE or ++
  164. FALSE. Without output the primitive succeeds or fails.
  165.  
  166. get-filter, 4 (32)
  167. 3
  168. Inputs:   ¥0D++
  169. Outputs:   TheFunctionPointer
  170. Inputs:   ¥0D++
  171. Outputs:   ABlock@
  172. Return TheFunctionPointer. ( Used for FileFilter argument in call to SFGetFile.)
  173.  
  174. The Main Routine in THINK C *563*
  175.  
  176. Each 'TGSC' code resource contains one main routine. This routine initializes Prograph primitive information at program startup.  The main routine is called once, during Prograph initialization. The code for the THINK C main routine from example_XPrims.c is as follows.
  177.  
  178. #if _INTERPRETER
  179.  
  180. /* main loads primitives into interpreter's XPrim table */
  181.  
  182. void main( table )
  183.  
  184. ProcPtr * table;      /* common table */
  185. {
  186.  asm 
  187.  { 
  188.   move.l a4, -(sp)     /* move A4 on to the stack */
  189.   move.l a0, a4      /* move address of code resource to A4 */
  190.  }
  191.  
  192.  ct = table;     /* set up common table for shared functions */
  193.  
  194.  AddPrimitive( 1, 0x0101, PF_USER, 0, &U_list_2D_average );
  195.  AddPrimitive( 2, 0x0101, PF_USER | PF_VAR, 0, 
  196.                &U_input_2D_average );
  197.  AddPrimitive( 3, 0x0200, PF_USER | PF_CTRL | PF_VAR, 0, 
  198.                &U_point_2D_in_2D_rect_3F_ );
  199.  AddPrimitive( 4, 0x0001, PF_USER, 0, &U_get_2D_filter );
  200.  
  201.  asm { move.l (sp)+, a4 }     /* move saved value back into A4 */
  202. }
  203.  
  204. #endif
  205.  
  206. The value of register A4 is set up at the beginning of the main routine. The current value of A4 is recorded, along with the primitive information, during a primitive窶冱 initialization. At the end of the main routine, the previous value of A4 is restored. Whenever a primitive is called, its saved A4 value is automatically restored. This allows the primitive to access any of the code resource窶冱 global or static data. 
  207. In the main routine, a call is made to AddPrimitive for each primitive in the 'TGSC' resource. 
  208.  
  209. Building Interpreted XPrims Using MPW C *564*
  210.  
  211. This section describes how to build and use the example XPrims using MPW C. 
  212.  
  213. u    Copy the folders XPExamples, XPIncludes and XPLibraries into your MPW Examples, Interfaces and Libraries folders respectively.
  214.  
  215. u    Insert the following lines into your MPW startup script and execute them:  
  216.  
  217.        Set XPIncludes "{MPW}Interfaces:  XPIncludes:  "
  218.    Export XPIncludes
  219.  
  220.        Set XPLibraries "{MPW}Libraries:  XPLibraries:  "
  221.    Export XPLibraries
  222.  
  223. u    Set the current directory to "{MPW}Example:  XPExamples" and execute the command:  
  224.  
  225.    make -f example_XPrims_I.make
  226.  
  227. u    Compile and build the code resource by executing the commands produced by the make command. The code resource file, example_XPrims, will be built with a File Type of 'TGSC' and Creator of TGSL. 
  228.  
  229. u Move example_XPrims into the same folder as Prograph and the example XPrims are ready to use.
  230.  
  231.  
  232. _______________________________________
  233. NOTE:    'TGSC' resources can be numbered arbitrarily. The maximum size of a 'TGSC' code resource is 32K bytes. However, if your code exceeds 32K, you can  set the MPW linker flag for code resources greater than 32K.
  234. ---------------------------------------
  235.  
  236.  
  237. Creating the 'STR#' Resources with MPW *564*
  238.  
  239. Each primitive should have a corresponding 'STR#' resource containing the primitive窶冱 name and help information; this will be displayed in Prograph窶冱 ヒ僮nfo窶ヲ dialog. 
  240.  
  241. In MPW, Rez can be used to append the 'STR#' resource to your primitive resource file. The file example_XPrims_I.r contains Rez source code for the 'STR#' resources for the example primitives. You can use this file as a template for creating your own 'STR#' resources. Here are the contents of example_XPrims_I.r:  
  242.  
  243. #include "Types.r"
  244.  
  245. resource 'STR#' (1, "list-average", purgeable) {
  246.  {    /* array StringArray:   3 elements */
  247.   /* [1] */
  248.   "Inputs:   TheList¥n"
  249.   "Outputs:   TheAverage",
  250.   /* [2] */
  251.   "Inputs:   list¥n"
  252.   "Outputs:   real",
  253.   /* [3] */
  254.   "Accept a list of numbers, return the average."
  255.  }
  256. };
  257.  
  258. resource 'STR#' (2, "input-average", purgeable) {
  259.  {    /* array StringArray:   3 elements */
  260.   /* [1] */
  261.   "Inputs:  TheNumber; [ TheNumber; 窶ヲ]¥n"
  262.   "Outputs:  TheAverage",
  263.   /* [2] */
  264.   "Inputs:   number; [number; 窶ヲ]¥n"
  265.   "Outputs:   real",
  266.   /* [3] */
  267.   "Accept 1 to n numeric inputs, return the average."
  268.  }
  269. };
  270.  
  271. resource 'STR#' (3, "point-in-rect?", purgeable) {
  272.  {    /* array StringArray:   3 elements */
  273.   /* [1] */
  274.   "Inputs:   ThePoint; TheRect¥n"
  275.   "Outputs:   [TheResult]",
  276.   /* [2] */
  277.   "Inputs:   point; rect¥n"
  278.   "Outputs:   [boolean]",
  279.   /* [3] */
  280.   "ThePoint is in TheRect? With output the "
  281.   "result is TRUE or FALSE. Without output "
  282.   "the primitive succeeds or fails."
  283.  }
  284. };
  285.  
  286. resource 'STR#' (4, "get-filter", purgeable) {
  287.  {    /* array StringArray:   3 elements */
  288.   /* [1] */
  289.   "Inputs:   ¥n"
  290.   "Outputs:   TheFunctionPointer",
  291.   /* [2] */
  292.   "Inputs:   ¥n"
  293.   "Outputs:   ABlock@",
  294.   /* [3] */
  295.   "Return TheFunctionPointer. ( Used for "
  296.   "FileFilter argument in call to SFGetFile.)"
  297.  }
  298. };
  299.  
  300. The Main Routine in MPW C *566*
  301.  
  302. Each 'TGSC' code resource contains one main routine. This routine initializes Prograph primitive information at program startup.  The main routine is called once, during Prograph initialization. The code for the MPW C main routine from example_XPrims.c is as follows.
  303.  
  304. #if _INTERPRETER
  305.  
  306. ProcPtr     * ct;
  307. Int4     PrographA5;
  308.  
  309. /* main - loads primitives into interpreter's XPrim table 
  310.  *      - creates area for global data
  311.  */
  312.  
  313. void main( table )
  314. ProcPtr * table;       /* common table */
  315. {
  316. Int4     XPrimA5;
  317. Handle     XPrimA5Handle;
  318.  
  319.  /* Create a global data area */
  320.  
  321.  XPrimA5Handle = NewHandle( (Nat4) A5Size());
  322.  
  323.  if ( XPrimA5Handle == NULL )
  324.   return;
  325.   
  326.  MoveHHi(XPrimA5Handle);
  327.  HLock( XPrimA5Handle );
  328.  XPrimA5 = *XPrimA5Handle + (Int4) A5Size() - 32;
  329.  A5Init( XPrimA5  );
  330.  
  331.  PrographA5 = SetA5( XPrimA5 ); /* Save value of A5 */
  332.  
  333.  ct = table;
  334.  
  335.  AddPrimitive( 1, 0x0101, PF_USER, 0, 
  336.          (ProcPtr) &U_list_2D_average );
  337.  AddPrimitive( 2, 0x0101, PF_USER | PF_VAR, 0, 
  338.          (ProcPtr) &U_input_2D_average );
  339.  AddPrimitive( 3, 0x0200, PF_USER | PF_CTRL | PF_VAR, 0, 
  340.          (ProcPtr) &U_point_2D_in_2D_rect_3F_ );
  341.  AddPrimitive( 4, 0x0001, PF_USER, 0, 
  342.          (ProcPtr) &U_get_2D_filter );
  343.  
  344.  SetA5( PrographA5 );     /* Restore the value of A5 */
  345. }
  346.  
  347. #endif
  348.  
  349. A global data area for the code resource is created at the beginning of the main routine and the current value of A5 is recorded. At the end of the main routine, the value of A5 is restored. The AddPrimitive routine records the A5 value of the code resource and whenever the primitive is called, this A5 value is automatically restored. If a primitive executes a supplied function which is a callback to the Prograph Interpreter the value of A5 is automatically saved and reset. This allows primitives to access the code resource窶冱 global or static data. 
  350.  
  351. In the main routine, a call is made to AddPrimitive for each primitive in the 'TGSC' resource. 
  352.  
  353. XPrims in Compiled Code *567*
  354.  
  355. The 'STR#' resource and the main routine required by the interpreter are not needed for compiled code. This is because the Prograph compiler first converts your C object code into it窶冱 own format, then links the converted object file directly with your compiled Prograph code. 
  356.  
  357.  
  358. Building Compiled XPrims Using THINK C *567*
  359.  
  360. To add the example primitives to a compiled application, perform the following steps:  
  361.  
  362. u Create a new THINK C project.
  363.  
  364. u Add the file example_XPrims.c to the project.
  365.  
  366. u Make sure the _INTERPRETER flag in X_includes.h is set to 0.
  367.  
  368. u Compile and build a library and save it in a file called example_XPrims.lib. 
  369.  
  370. u Include example_XPrims.lib in your Prograph project.
  371.  
  372. Building Compiled XPrims Using MPW C *567*
  373.  
  374. To add the example primitives to a compiled application, perform the following steps:  
  375.  
  376. u    Copy the folders XPExamples, XPIncludes and XPLibraries into your MPW Examples, Interfaces and Libraries folders respectively.
  377.  
  378. u    Insert the following lines into your MPW start up script and execute them:  
  379.  
  380.        Set XPIncludes "{MPW}Interfaces:  XPIncludes:  "
  381.    Export XPIncludes
  382.  
  383.        Set XPLibraries "{MPW}Libraries:  XPLibraries:  "
  384.    Export XPLibraries
  385.  
  386. u    Set the current directory to "{MPW}Example:  XPExamples" and execute the command:  
  387.  
  388.    make -f example_XPrims_C.make
  389.  
  390. u    Compile the example program by executing the command produced by the make command. This will create the object file example_XPrims_C.c.o.
  391.  
  392. u Include the object file example_XPrims_C.c.o and the library MPWLibrary in your Prograph project.
  393.  
  394.  Example XPrims *568*
  395.  
  396. This section describes the four example XPrims. Note that the code is the same for MPW C and THINK C. 
  397.  
  398. Example # 1 
  399.  
  400. A fixed arity primitive, called list-average, with one input, consisting of the list of numbers to be averaged, and one output, the average of the numbers.
  401.  
  402. /* list-average - accept a C_list of numbers, return the average 
  403.                    value of the list as a C_real */
  404.  
  405. Nat2 U_list_2D_average( input, output )
  406.  
  407. C_list *input;      /* C_list of numbers */
  408. C_real **output;     /* address to put handle of output value */
  409.  
  410. {
  411. Nat2     inarity;      /* number of inputs */
  412. Nat2     outarity;     /* number of outputs */
  413. Nat2    num_elements;    /* number of elements summed */
  414. Nat2     index;       /* current position in the list */
  415. Handle item;       /* generic handle to list item */
  416. Real     total;       /* total of items */
  417.  
  418.  GETARITY( inarity, outarity )
  419.  
  420. #if _INTERPRETER
  421.  if ( inarity != 1 || outarity != 1 )
  422.   return PRIMERR_ARITY;        /* bad arity */
  423.  
  424.  if ( !IsType( input, C_LIST )  )
  425.   return PRIMERR_TYPE + 1;       /* wrong type on input 1 */
  426. #endif
  427.  
  428.  num_elements = (**input).length;     /* extract size for speed */
  429.  
  430. #if _INTERPRETER
  431.  if ( num_elements == 0 )
  432.   return PRIMERR_VALUE + 1;       /* bad value on input 1 */
  433. #endif
  434.  
  435.  for(index=0, total=0.0; index < (**input)length; index++)
  436.  {
  437.   item = (**input).data[index];    /* get item from list */
  438.   
  439.   if ( IsType( item, C_INTEGER ) )
  440.    total += ( **(C_integer *) item ).value;
  441.   else if ( IsType( item, C_REAL ) )
  442.    total += ( **(C_real *) item ).value;
  443. #if _INTERPRETER
  444.   else
  445.    return PRIMERR_VALUE +1;      /* type not numeric */
  446. #endif
  447.  }
  448.  
  449.  *output = MakeC_real( total/num_elements );     
  450.  
  451.  return PCF_TRUE;         /* no errors encountered */
  452. }
  453.  
  454.  
  455. If inarity is not one and outarity is not one, the error code PRIMERR_ARITY is returned. 
  456.  
  457. The IsType function verifies the type of input. If the item is not a C_list, PRIMERR_TYPE+1 is returned, indicating a type error on input 1. 
  458.  
  459. The length of the list is extracted. If the size is zero, PRIMERR_VALUE+1 is returned, indicating a value error on input 1. (The size must be nonzero to avoid division by zero when calculating the average.)
  460.  
  461. Each item in the list is extracted and its type checked. If a particular item is neither an integer nor a real, a type error is returned for input 1; otherwise, the item窶冱 value is added to a running total.
  462.  
  463. The average is computed, passed to the MakeC_real function, and assigned to the output root.  The only 窶徘ermanent窶 reference to the new C_real is on the output root, so the use count of one automatically provided by MakeC_real is correct.
  464.  
  465. The very last action of a primitive is usually to return the value PCF_TRUE  This indicates that the call to the primitive operation has completed without error, and basically instructs the interpreter or compiled code to proceed to the next operation.
  466.  
  467. Example # 2 *570*
  468.  
  469. A variable-arity primitive, called input-average, that returns the average value of its variable number of inputs.
  470.  
  471. /* input-average - accept 1 to n numeric inputs, return the
  472.        average value of the inputs as a C_real */
  473.  
  474. Nat2 U_input_2D_average( args )
  475.  
  476. C_object *args;       /* input & output args */
  477.  
  478. {
  479. C_object *input;      /* generic pointer to input args */
  480. C_object **output;      /* generic pointer to output arg places */
  481. Nat2      inarity;      /* # inputs */
  482. Nat2      outarity;     /* # outputs */
  483. Int2      index;       /* current input */
  484. C_object *item;       /* generic handle to input  item */
  485. Real10     total;       /* total of inputs */
  486. Nat2     num_elements;    /* number of elements summed */
  487.  
  488.  VARITY( args, inarity, outarity, input, output );
  489.                /* variable arity setup */
  490.  
  491. #if _INTERPRETER
  492.  if( inarity < 1 || outarity != 1 )
  493.   return PRIMERR_ARITY;       /* bad minimum  arity */
  494. #endif
  495.  
  496.  num_elements = inarity;
  497.  
  498.  for( index = 0, total = 0.0 ; index < inarity; index++ )
  499.  {
  500.   item = input[index];        /* get item from input */
  501.  
  502.   if ( IsType( item, C_INTEGER ) )
  503.    total += ( **(C_integer *) item ).value;
  504.   else if ( IsType( item, C_REAL ) )
  505.    total += ( **(C_real *) item ).value;
  506. #if _INTERPRETER
  507.   else
  508.    return PRIMERR_VALUE + index + 1;     /* type not numeric */
  509. #endif
  510.  }
  511.  
  512.  *output[0] = MakeC_real( total/num_elements );     
  513.  return PCF_TRUE;         /* no errors encountered */
  514. }
  515.  
  516.  
  517. This example shows how to create a variable-arity primitive. First the VARITY macro unpacks the primitive窶冱 inarity, outarity, inputs, and outputs. A check is then made on the range of the calling arity. This call must have at least one input and can have only one output; otherwise an arity error is returned.
  518.  
  519. The function iterates through the array of inputs, adding the input value to the total depending on the input窶冱 type. If the type of the input is neither C_integer nor C_real, a type error is returned together with the ordinal position of the invalid input.
  520.  
  521. In this example, the output is an array of addresses where output data can be placed. 
  522. In this case, there is only one output. The average is passed to the MakeC_real function and assigned to the output root.
  523.  
  524. The return value PCF_TRUE indicates that the primitive has completed without error.
  525.  
  526. Example # 3 *571*
  527.  
  528. A fixed-arity boolean primitive called point-in-rect?, which takes a point (or a pointer or handle to a point) and a rectangle (or a pointer or handle to a rectangle) and determines if the point falls within the rectangle. This primitive is initialized with a PF_CTRL flag set to indicate that it should be created with a next-case control. 
  529.  
  530. If the call to the primitive has no output then it will either succeed or fail. If it has an output then the primitive will succeed and will return a C_boolean data item set to either TRUE or FALSE.
  531.  
  532.  /* point-in-rect? - boolean prim to determine if point is in a 
  533.           rectangle */
  534.  
  535. Nat2 U_point_2D_in_2D_rect_3F_( input1, input2, output )
  536.  
  537. C_Point     *input1;     /* input arg #1, the point  */
  538. C_Rect      *input2;     /* input arg #2, the rectangle */
  539. C_boolean    **output;    /* the result, if out arity = 1 */
  540.  
  541. {
  542. Nat2    inarity;       /* # inputs */
  543. Nat2    outarity;      /* # outputs */
  544. Rect    r;         /* value of input 1 */
  545. Point    p;         /* value of input 2 */
  546. Bool    result;       /* result of point in rect */
  547.  
  548.  GETARITY( inarity, outarity )
  549.  
  550. #if _INTERPRETER
  551.  if ( inarity != 2 || outarity > 1 )
  552.   return PRIMERR_ARITY;       /* bad arity */
  553.  
  554.  if ( !HasType( input1, C_POINT ) )
  555.   return PRIMERR_TYPE + 1;      /* wrong type on input 1 */
  556.  
  557.  if ( !HasType( input2, C_RECT ) )
  558.   return PRIMERR_TYPE + 2;      /* wrong type on input 2 */
  559. #endif
  560.  
  561.  switch ( GetRefLevel( input1 ) )
  562.  {
  563.   case 2:              /* handle to point*/
  564.    p = **(Point **)(**(C_Handle *)input1).value;
  565.    break;
  566.   case 1:              /* pointer to point*/
  567.    p = *(Point *)(**(C_Ptr *)input1).value;
  568.    break;
  569.   default:              /* point */
  570.    p = (**input1).value;       
  571.  }
  572.  
  573.  switch ( GetRefLevel( input2 ) )
  574.  {
  575.   case 2:              /* handle to rect */
  576.    r = **(Rect **)(**(C_Handle *)input2).value;
  577.    break;
  578.   case 1:              /* pointer to rect */
  579.    r = *(Rect *)(**(C_Ptr *)input2).value;
  580.    break;
  581.   default:              /* rect */
  582.    r = (**input2).value;     
  583.  }
  584.  
  585.  result = PtInRect( p, &r );
  586.  
  587.  if ( outarity == 1 )
  588.   *output = MakeC_boolean( result );
  589.  else if ( result == FALSE )    
  590.   return PCF_FALSE;
  591.  
  592.  return PCF_TRUE;
  593. }
  594.     
  595.  
  596. Since it is valid for this primitive to have either one or no outputs, the VARITY macro could have been used. VARITY was not used, partly for the sake of illustration, and partly because there is no need to set the inputs and outputs up as arrays. 
  597.  
  598. First, the inarity and outarity are extracted and an arity range check is made.  Checks are then made to ensure that input1 and input2 refer to a point and a rectangle, respectively. The supplied function HasType returns TRUE if input1窶冱 data item is a point, or a pointer or handle to a point; otherwise a type error is returned indicating which input is incorrect. 
  599.  
  600. The function GetRefLevel switches to an appropriate case, based on the data item窶冱 level of indirection, and assigns the point to p and the rectangle to r. 
  601.  
  602. The Toolbox routine PtInRect() is called.  If an output root was specified, the result is packaged into a C_boolean and placed on the root, and PCF_TRUE is returned to indicate successful completion.  
  603.  
  604. If the primitive does not have an output, the result of the PtInRect() call is returned as the function result:   PCF_TRUE for TRUE, PCF_FALSE for FALSE.
  605.  
  606. Example # 4 *573*
  607.  
  608. Certain advanced features of the Macintosh interface are accomplished by passing function pointers to Toolbox calls.  Such a custom function must be written in C in a code resource; the code resource should also contain an XPrim that returns the address of the custom function.  From Prograph, you can then call the XPrim and pass the output to a Mac Method call.
  609.  
  610. The following example contains a filter function for the SFGetFile procedure and an XPrim, called get-filter, that returns the address of the filter function.  The address of the filter function is then returned as the output of the primitive get-filter.
  611.  
  612. #if _INTERPRETER
  613.  
  614. /* display only those files whose names begin with e or E */
  615.  
  616. pascal Boolean FileFilter( block )
  617.  
  618. ParmBlkPtr block;
  619.  
  620. {
  621. char c;
  622.  
  623.  c = block->fileParam.ioNamePtr[1];
  624.  
  625.  if ( c == 'e' || c == 'E' )
  626.         return FALSE;
  627.     else
  628.         return TRUE;
  629. }
  630.  
  631. /* get-filter - return pointer to FileFilter as an ABlock@ */
  632.  
  633. Nat2 U_get_2D_filter( output )
  634.  
  635.  
  636. C_Ptr **output;    /* address to put handle of output value */
  637.  
  638. {
  639. Nat2    inarity;      /* # inputs */
  640. Nat2    outarity;     /* # outputs */
  641.     
  642.  GETARITY( inarity, outarity )
  643.  
  644.  if ( inarity != 0 || outarity != 1 )
  645.   return PRIMERR_ARITY;      /* bad arity */
  646.  
  647.     *output = MakeC_Ptr( NIL, &FileFilter );
  648.  return PCF_TRUE;        /* no errors encountered */
  649. }
  650.  
  651. #endif
  652.  
  653.  
  654. The function FileFilter, declared as using pascal calling conventions, returns a boolean value of FALSE if the file is to be included in the dialog窶冱 list, or TRUE if it is not. The first character of the file窶冱 name is examined.
  655.  
  656. The get-filter primitive first checks its arity. If the arity is correct, the address of the FileFilter function is passed to a new C_Ptr and assigned to the primitive窶冱 output root. The function then returns PCF_TRUE to indicate completion without error. 
  657.